<?php
namespace Home\Controller;
use Think\Controller;

class IndexController extends Controller
{
    /**
     * index 
     * 
     * 登录操作
     * @access public
     * @return void
     */
    public function index()
    {
        //登录操作
        if(IS_POST){
            $username = trim(I('POST.username'));
            $password = trim(I('POST.pwd'));
            $users = M('user');

            $pwd = $users->where("username = '$username'")->getField('pwd');
            if(md5($password) == $pwd){
                cookie('username',$username,3600);
                cookie('pwd',$password,3600);
                return $this->welcome();
            }
        }

        //不存在用户或者没密码就跳转登录
        if(cookie('username') == null || cookie('pwd') == null){
            return $this->display('User/login');
        }

        //欢迎
        return $this->welcome();
    }

    /**
     * welcome 
     * 
     * 登录后跳转
     * @access protected
     * @return void
     */
    protected function welcome()
    {
        if(cookie('username') == null || cookie('pwd') == null){
            return redirect('/drm/');
        }
        $person['name'] = cookie('username');
        $notice = $this->getNotice();//获取临近过期条数
        cookie('over_drugs', $notice);
        $this->assign('person',$person);
        return $this->display('welcome');
    }

    /**
     * getNotice 
     * 
     * 获取推送
     * @access protected
     * @return void
     */
    protected function getNotice()
    {
        if($username = cookie('username') && $pwd = cookie('pwd')){
            $drugs = M('drugs');
            $alert_time = time()+604800;//7*24*3600
            $query['period'] = array('lt',$alert_time);
            $over_drugs = $drugs->where($query)->select();
            return count($over_drugs);
        }
        return redirect('/drm/');
    }
}
